$(function () {
    var xhr = new XMLHttpRequest;
    xhr.onloadend = function () {
        if (xhr.status == 200) {
            total = JSON.parse(xhr.responseText)
            show()
        } else {

        }
    }

    xhr.open('get', 'http://localhost/mi/mi.json');
    xhr.send(null);
    let htmlStr = '';
    let numran = Math.floor(Math.random() * 100)
    const ul = document.querySelector('.cart-recommend ul');
    function show() {
        for (let i = numran; i < numran + 10; i++) {
            // console.log(i);
            htmlStr += `
                        <li>
                            <a class="goods-detail" href="http://localhost/mi/detail/">
                                <img src="${total[i].imgurl}" width = '140px' alt="">
                                <p class="p1">${total[i].name}</p>
                                <p class="p3">${total[i].price}元</p>
                                <p><span class="p4" style="display:none">${total[i].id}</span>${(Math.random() * 100).toFixed(1)}万人好评</p>
                                <p class="p2" style="display:none">${total[i].describe}</p>

                            </a>
                            <div class="join"><a class="in" href="javascript:;">加入购物车</a></div>
                        </li>
                        `
        }
        ul.innerHTML = htmlStr;
        var detailList
        if (detailList == null || detailList.length == 0) {
            detailList = []
        }
        $('.goods-detail').click(function () {
            console.log($(this));
            var goodObj = {
                id: $(this).find('.p4').last().text(),
                imgurl: $(this).find('img')[0].src,
                name: $(this).find('.p1').html(),
                describe: $(this).find('.p2').html(),
                price: parseInt($(this).find('.p3').html()),
                num: 1
            };
            console.log(goodObj.id, goodObj.imgurl, goodObj.name, goodObj.describe, goodObj.price);

            if (detailList.length === 0) {
                // 添加到detailList
                detailList.push(goodObj);
            } else {
                for (var i = 0; i < detailList.length; i++) {
                    // 如果商品已经存在cookie中，则数量+1
                    if (detailList[i].id === goodObj.id) {
                        detailList[i].num++;
                        localStorage.setItem('detaillist', JSON.stringify(detailList))
                        break
                    }
                } if (i === detailList.length) {
                    // 添加到detailList
                    detailList.push(goodObj);
                    localStorage.setItem('detaillist', JSON.stringify(detailList))
                }
            }
            localStorage.setItem('detaillist', JSON.stringify(detailList))
        })

    }
})